package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.RedisData;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;

    @Resource
    private CacheClient cacheClient;
    /**
     *使用缓存根据id查询商户信息
     * @param id
     * @return
     */
    public Result queryByID(Long id){
        //工具类解决缓存穿透
        //Shop shop = cacheClient.queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY,id,Shop.class, this::getById,RedisConstants.CACHE_SHOP_TTL,TimeUnit.MINUTES);
        //

        //缓存穿透
        //Shop shop = queryWithPassThrough(id);

        //击穿
        Shop shop = cacheClient.quertWithLogicalExpire(RedisConstants.CACHE_SHOP_KEY,id,Shop.class, this::getById,20L,TimeUnit.SECONDS);

        // 互斥锁解决缓存击穿
        //Shop shop = queryWithMutex(id);

        //逻辑过期方案解决缓存击穿
        //Shop shop = quertWithLogicalExpire(id);

        //布隆过滤器
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter("shop:queryBloom");
        bloomFilter.tryInit(55000000L,0.03);

        //数据库获取
        //shop = getById(id);

        if(shop == null){
            return Result.fail("店铺不存在");
        }
        //返回
        return Result.ok(shop);
    }
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public Shop quertWithLogicalExpire(Long id){

        String key= RedisConstants.CACHE_SHOP_KEY+id;//long能直接加在string上？

        //查询redis是否存在
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //存在返回
        if(StrUtil.isBlank(shopJson)){
            return null;
        }
        //redis反序列化
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class);
        //判断过期时间

        LocalDateTime expirTime = redisData.getExpireTime();
        //未过期返回

        if(expirTime.isAfter(LocalDateTime.now())){
            return shop;
        }

        //已过期
        //缓存重建

        String lockKey = RedisConstants.LOCK_SHOP_KEY+id;


            //获取互斥锁
            boolean isLock = tryLock(lockKey);

            if(isLock){
                //开启独立线程，实现缓存重建
                CACHE_REBUILD_EXECUTOR.submit(()->{
                    try {
                        this.saveShop2Redis(id,20L);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    } finally {
                        unlock(lockKey);
                    }

                });
            }
        //返回
        return shop;
    }
    public void saveShop2Redis(Long id,Long expireSeconds) throws InterruptedException {
        Shop shop= getById(id);

        Thread.sleep(50);

        RedisData redisData=new RedisData();
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        redisData.setData(shop);

        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id ,JSONUtil.toJsonStr(redisData));
    }
    public Shop queryWithMutex(Long id){

        String key= RedisConstants.CACHE_SHOP_KEY+id;//long能直接加在string上？

        //查询redis是否存在
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //存在返回
        if(StrUtil.isNotBlank(shopJson)){

            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }

        if(shopJson !=null ){
            return null;
        }
        //不存在查数据库

        //实现缓存重建

        //获取互斥锁

        String lockKey = RedisConstants.LOCK_SHOP_KEY+id;
        Shop shop = null;
        try {
            boolean isLock = tryLock(lockKey);


            //失败
            if(!isLock){
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //成功


            shop = getById(id);
            //模拟延时
            Thread.sleep(200);

            //数据库不存在报错
            if(shop == null){
                stringRedisTemplate.opsForValue().set(key,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);
                return null;
            }
            //写入缓存
            String jsonStr = JSONUtil.toJsonStr(shop);

            stringRedisTemplate.opsForValue().set(key,jsonStr,RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        finally {
            unlock(lockKey);
        }

        //返回
        return shop;
    }
    public Shop queryWithPassThrough(Long id){
        String key= RedisConstants.CACHE_SHOP_KEY+id;//long能直接加在string上？

        //查询redis是否存在
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //存在返回
        if(StrUtil.isNotBlank(shopJson)){

            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        if(shopJson !=null ){
            return null;
        }
        //不存在查数据库
        Shop shop = getById(id);

        //数据库不存在报错
        if(shop == null){
            stringRedisTemplate.opsForValue().set(key,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        //写入缓存
        String jsonStr = JSONUtil.toJsonStr(shop);

        stringRedisTemplate.opsForValue().set(key,jsonStr,RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //返回
        return shop;
    }
    /**
     * 商品更新，包含缓存删除
     * @param shop
     * @return
     */
    @Transactional
    public Result update(Shop shop){
        Long id = shop.getId();
        if(id == null){
            return Result.fail("用户id为空");
        }

        boolean update = updateById(shop);
        if(!update){
            return Result.fail("更新失败");
        }

        stringRedisTemplate.opsForHash().delete(RedisConstants.CACHE_SHOP_KEY+shop.getId());
        return Result.ok();
    }
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1",10,TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }
}
